package bma.common.netty.webserver;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Set;
import java.util.TimeZone;

import javax.activation.MimetypesFileTypeMap;

import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.handler.codec.http.Cookie;
import org.jboss.netty.handler.codec.http.CookieDecoder;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpHeaders.Names;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.util.CharsetUtil;

import bma.common.langutil.log.acclog.AccessLog;
import bma.common.netty.webserver.common.RequestFormCommon;

public class WebServerUtil {

	public static final String HTTP_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz";
	public static final String HTTP_DATE_GMT_TIMEZONE = "GMT";

	public static String sanitizeUri(String uri) {
		// Decode the path.
		try {
			uri = URLDecoder.decode(uri, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			try {
				uri = URLDecoder.decode(uri, "ISO-8859-1");
			} catch (UnsupportedEncodingException e1) {
				throw new Error();
			}
		}

		// Convert file separators.
		uri = uri.replace('/', File.separatorChar);

		// Simplistic dumb security check.
		// You will have to do something serious in the production environment.
		if (uri.contains(File.separator + '.')
				|| uri.contains('.' + File.separator) || uri.startsWith(".")
				|| uri.endsWith(".")) {
			return null;
		}

		return uri;
	}

	public static void writeAndClose(Channel ch, Object response) {
		if (ch.isConnected()) {
			// Close the connection as soon as the error message is sent.
			ch.write(response).addListener(ChannelFutureListener.CLOSE);
		}
	}

	public static void writeAndKeepAlive(String ltag, RequestContext ctx,
			Object response) {
		Channel ch = ctx.getChannel();
		HttpRequest request = ctx.getRequest();
		if (ch.isConnected()) {
			ChannelFuture writeFuture = ch.write(response);
			// Decide whether to close the connection or not.
			if (!HttpHeaders.isKeepAlive(request)) {
				// Close the connection when the whole content is written out.
				writeFuture.addListener(ChannelFutureListener.CLOSE);
			}
			endWith200(ltag, ctx);
		} else {
			end(ltag, ctx);
		}
	}

	public static void endWith200(String ltag, RequestContext ctx) {
		AccessLog log = ctx.getAccessLog();
		if (log != null && log.isInfoEnabled()) {
			log.info(ltag, "end", 200);
		}
	}

	public static void end(String ltag, RequestContext ctx) {
		AccessLog log = ctx.getAccessLog();
		if (log != null && log.isInfoEnabled()) {
			log.info(ltag, "end", 0);
		}
	}

	public static void endWithStatus(String ltag, RequestContext ctx,
			HttpResponseStatus status) {
		HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
				status);
		response.setHeader(Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
		response.setContent(ChannelBuffers.copiedBuffer(
				"Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
		writeAndClose(ctx.getChannel(), response);
		AccessLog log = ctx.getAccessLog();
		if (log != null && log.isInfoEnabled()) {
			log.info(ltag, "end", status.getCode());
		}
	}

	/**
	 * send 50X
	 * 
	 * @param ctx
	 *            Context
	 */
	public static void endWithError(String ltag, RequestContext ctx, Throwable e) {
		HttpResponseStatus st = HttpResponseStatus.INTERNAL_SERVER_ERROR;
		if (e != null) {
			String msg = e.getMessage();
			if (msg != null && msg.startsWith("timeout"))
				st = HttpResponseStatus.GATEWAY_TIMEOUT;
		}
		endWithStatus(ltag, ctx, st);
	}

	/**
	 * send 404
	 * 
	 * @param ctx
	 *            Context
	 */
	public static void endWithNotFound(String ltag, RequestContext ctx) {
		endWithStatus(ltag, ctx, HttpResponseStatus.NOT_FOUND);
	}

	/**
	 * Sets the Date header for the HTTP response
	 * 
	 * @param response
	 *            HTTP response
	 */
	public static void setDateHeader(HttpResponse response) {
		SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT,
				Locale.US);
		dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

		Calendar time = new GregorianCalendar();
		response.setHeader(Names.DATE, dateFormatter.format(time.getTime()));
	}

	/**
	 * Sets the Date and Cache headers for the HTTP Response
	 * 
	 * @param response
	 *            HTTP response
	 * @param fileToCache
	 *            file to extract content type
	 */
	public static void setDateAndCacheHeaders(HttpResponse response,
			long lastModified, int cacheTime) {
		SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT,
				Locale.US);
		dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

		// Date header
		Calendar time = new GregorianCalendar();
		response.setHeader(Names.DATE, dateFormatter.format(time.getTime()));

		// Add cache headers
		if (cacheTime > 0) {
			time.add(Calendar.SECOND, cacheTime);
			response.setHeader(Names.EXPIRES,
					dateFormatter.format(time.getTime()));
			response.setHeader(Names.CACHE_CONTROL, "private, max-age="
					+ cacheTime);
		}
		if (lastModified > 0) {
			response.setHeader(Names.LAST_MODIFIED,
					dateFormatter.format(new Date(lastModified)));
		}
	}

	/**
	 * Sets the content type header for the HTTP Response
	 * 
	 * @param response
	 *            HTTP response
	 * @param file
	 *            file to extract content type
	 */
	public static void setContentTypeHeader(HttpResponse response,
			String filePath) {
		MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
		response.setHeader(Names.CONTENT_TYPE,
				mimeTypesMap.getContentType(filePath));
	}

	public static Set<Cookie> getCookies(HttpRequest request) {
		String cookieString = request.getHeader(HttpHeaders.Names.COOKIE);
		if (cookieString != null) {
			CookieDecoder cookieDecoder = new CookieDecoder();
			return cookieDecoder.decode(cookieString);
		}
		return Collections.emptySet();
	}

	public static RequestForm getForm(HttpRequest request) {
		return new RequestFormCommon(request);
	}

	public static RequestForm getForm(RequestContext ctx) {
		return getForm(ctx.getRequest());
	}
}
